<template>
  <div class="login">
    <span class="close">
      <i class="iconfont iconicon-test"></i>
    </span>
    <h2 class="logo">
      <i class="iconfont iconnew"></i>
    </h2>
    <Input
      v-model="user.username"
      type="text"
      placeholder="用户名/手机号"
      :rules="rules.username"
      msg="手机号码格式错误"
    ></Input>
    <!--自定义v-model-->
    <Input
      v-model="user.password"
      type="password"
      placeholder="密码"
      :rules="rules.password"
      msg="密码格式错误"
    ></Input>

    <div>
      <div class="tips">
        <router-link to="/reigster">还没有账号？去注册</router-link>
      </div>
    </div>
    <MyButton
      @fn="loginFn"
      :url="$route.query.url"
      :newsid="$route.query.newsid"
      type="primary"
    >
      登录
    </MyButton>
  </div>
</template>

<script>
//样式
import "../styles/reigsterlogin.css";
//页面组件
import MyButton from "../components/MyButton";
import Input from "../components/input.vue";
//api
import { userLoginApi } from "../apis/user.js";
import { setToken ,getGoUrl} from "../utils/tokenData";
export default {
  mounted() {},
  data() {
    return {
      user: {
        username: "13488888888",
        password: "555",
      },
      rules: {
        username: /^1\d{10}$|^[a-zA-Z]\w{2,10}$|^1\d{4,5}$/,
        password: /^[a-zA-Z0-9~!@#$%^&*()_+=]{3,18}$/,
      },
    };
  },
  components: {
    MyButton,
    Input,
  },

  methods: {
    async loginFn() {
      if (!this.rules.username.test(this.user.username)) {
        this.$notify("账号格式错误，请输入正确的手机号");
        return;
      }
      if (!this.rules.password.test(this.user.password)) {
        this.$notify("密码格式错误，请输入3到18位数字字母或符号");
        return;
      }

      const res = await userLoginApi(this.user);
      const { message } = res.data;
      if (message == "登录成功") {
        this.$toast.success("登录成功");
        const { token } = res.data.data;
        setToken(token);
        const id = res.data.data.user.id;
        localStorage.setItem("hmttID", id);
        // console.log(getGoUrl());
        const from = getGoUrl()
        console.log(from);
        if(from){
          location.href=from
        }
        // this.$router.push({
        //   path: "/user",
        //   query: { id },
        // });
      } else {
        this.$toast.fail("用户名或密码错误");
      }
      
    },
  },
};
</script>

<style lang="less" scoped>
</style>